package com.share.zabbix.method;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.share.zabbix.request.ZabbixRequest;
import com.share.zabbix.request.ZabbixRequestBuilder;
import com.share.zabbix.response.ZabbixResponseUserLogin;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class ZabbixBaseMethod {

	protected static final Log log = LogFactory.get();

//	private static String zabbixUrl = "http://10.124.31.100:8027/api_jsonrpc.php";
	private static String zabbixUrl = "http://192.168.138.130/zabbix/api_jsonrpc.php";
//	private static String zabbixUrl = "http://10.20.67.47/zabbix/api_jsonrpc.php";

	private static String zabbixUser = "Admin";

	private static String zabbixPasswd = "zabbix";

	protected static final String ZABBIX_KEY_RESULT = "result";

	private static final String ZABBIX_KEY_APIINFO = "apiinfo.version";

	private static URI uri;

	private static volatile String auth;

	private static CloseableHttpClient httpClient;
	
	public static synchronized void auth(String url, String user, String password) {
		zabbixUrl = url;
		zabbixUser = user;
		zabbixPasswd = password;
	}

	private static void init() {
		if (StrUtil.isEmpty(zabbixUrl)) {
			return;
		}
		log.info("Zabbix初始化 : {}", zabbixUrl);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000)
				.setConnectionRequestTimeout(5 * 1000).setSocketTimeout(5 * 1000).build();
		PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
		CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager)
				.setDefaultRequestConfig(requestConfig).build();
		setUrl(zabbixUrl);
		setHttpClient(httpclient);
		login();
	}

	/**
	 * zabbix登录验证是否成功
	 * 
	 * @return
	 */
	private static boolean login() {
		if (StrUtil.isEmpty(zabbixUrl)) {
			return false;
		}
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder().paramEntry("user", zabbixUser)
				.paramEntry("password", zabbixPasswd).method("user.login").build();
		try {
			HttpUriRequest httpRequest = org.apache.http.client.methods.RequestBuilder.post().setUri(uri)
					.addHeader("Content-Type", "application/json")
					.setEntity(new StringEntity(JSON.toJSONString(request), ContentType.APPLICATION_JSON)).build();
			CloseableHttpResponse response = httpClient.execute(httpRequest);
			HttpEntity entity = response.getEntity();
			byte[] data = EntityUtils.toByteArray(entity);
			Gson gson = new GsonBuilder().create();
			ZabbixResponseUserLogin userLogin = gson.fromJson(JSON.parse(data).toString(),
					ZabbixResponseUserLogin.class);
			if (!StrUtil.isEmpty(userLogin.getAuth())) {
				log.info("Zabbix登录成功 !");
				auth = userLogin.getAuth();
				log.info("返回的token值：" + auth);
				return true;
			}
		} catch (IOException e) {
			log.error("zabbix登录失败!");
		}
		return false;
	}

	private static void setUrl(String url) {
		try {
			uri = new URI(url.trim());
		} catch (URISyntaxException e) {
			throw new RuntimeException("zabbix url invalid", e);
		}
	}

	private static void setHttpClient(CloseableHttpClient client) {
		httpClient = client;
	}

	public static String getApiVersion() {
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("apiinfo.version").build();
		JSONObject response = call(request);
		return response.getString("result");
	}

	/**
	 * zabbix接口调度公共方法
	 * 
	 * @param request
	 * @return
	 */
	protected static JSONObject call(ZabbixRequest request) {
		if (uri == null || httpClient == null)
			init();
		if (request.getAuth() == null && !request.getMethod().equalsIgnoreCase(ZABBIX_KEY_APIINFO)
				&& !"user.login".equalsIgnoreCase(request.getMethod())) {
			if (StrUtil.isEmpty(auth)) {
				login();
			}
			request.setAuth(auth);
		}
		try {
			HttpUriRequest httpRequest = org.apache.http.client.methods.RequestBuilder.post().setUri(uri)
					.addHeader("Content-Type", "application/json")
					.setEntity(new StringEntity(JSON.toJSONString(request), ContentType.APPLICATION_JSON)).build();
			CloseableHttpResponse response = httpClient.execute(httpRequest);
			HttpEntity entity = response.getEntity();
			byte[] data = EntityUtils.toByteArray(entity);
			JSONObject jsonObject = JSONObject.parseObject(JSON.parse(data).toString());
			return jsonObject;
		} catch (IOException e) {
			log.error("Zabbix接口错误!");
		}
		return null;
	}
	

}
